package com.GGG.cloud.house.agent.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.GGG.cloud.house.agent.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;

import java.util.Collection;
import java.util.List;

/**
 * @param <T>
 * @param <ID>
 * @param <BaseMapper>
 * @author 老九学堂
 * @copyright 老九学堂
 */
public abstract class BaseServiceImpl<T, ID, BaseMapper extends Mapper<T>> implements BaseService<T, ID> {

    /**
     * 关联的数据操作的Mapper对象
     */
    @Autowired
    protected BaseMapper baseMapper;

    @Override
    public boolean save(T record) {
        return baseMapper.insertSelective(record) == 1;
    }

    @Override
    public boolean saveWithNull(T record) {
        return baseMapper.insert(record) == 1;
    }

    @Override
    public boolean save(Collection<T> records) {
        for (T record : records) {
            this.save(record);
        }
        return true;
    }

    @Override
    public boolean saveWithNull(Collection<T> records) {
        for (T record : records) {
            this.saveWithNull(record);
        }
        return true;
    }

    @Override
    public boolean remove(ID id) {
        return baseMapper.deleteByPrimaryKey(id) == 1;
    }

    @Override
    public boolean remove(ID[] ids) {
        for (ID id : ids) {
            this.remove(id);
        }
        return true;
    }

    @Override
    public boolean update(T record) {
        return baseMapper.updateByPrimaryKeySelective(record) == 1;
    }

    @Override
    public boolean updateWithNull(T record) {
        return baseMapper.updateByPrimaryKey(record) == 1;
    }

    @Override
    public T get(ID id) {
        return baseMapper.selectByPrimaryKey(id);
    }

    @Override
    public T getByCondition(T condition) {
        return baseMapper.selectOne(condition);
    }


    @Override
    public List<T> listAll() {
        return baseMapper.selectAll();
    }

    @Override
    public List<T> listByCondition(T condition) {
        return baseMapper.select(condition);
    }

    @Override
    public Page<T> listByPageAndCondition(int pageIndex, int pageSize, T condition) {
        Page<T> page = PageHelper.startPage(pageIndex, pageSize);
        baseMapper.select(condition);
        return page;
    }
}
